package com.ccys.db.service.impl;



import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ccys.common.annotations.LogAnalysisAnnexTag;
import com.ccys.common.util.Kit;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.entity.TblAuditTrail;
import com.ccys.db.mapper.TblAuditTrailMapper;

import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Table;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * tbl_audit_trail管理
 */
@Service
@Slf4j
public class BaseTblAuditTrailWebServiceImpl extends BaseServiceImpl<TblAuditTrail> implements BaseTblAuditTrailWebService {

    @Autowired(required = false)
    private TblAuditTrailMapper tblAuditTrailMapper;


    @Override
    public void saveTblAuditTrail(String objId, String objSubId, Integer action, String jsonInfo, String tableName) {
        HttpServletRequest request = Kit.getRequest();
        String ip = null;
        String systemInfo = null;
        if(request != null) {
            ip = request.getRemoteAddr();
            systemInfo = request.getHeader("User-Agent");
        }
        TblAuditTrail tblAuditTrail = new TblAuditTrail();
        tblAuditTrail.setObjId(objId);
        tblAuditTrail.setObjSubId(objSubId);
        tblAuditTrail.setTableName(tableName);
        tblAuditTrail.setAction(action);
        tblAuditTrail.setJsonInfo(jsonInfo);
        tblAuditTrail.setIp(ip);
        tblAuditTrail.setSystemInfo(systemInfo);
        this.tblAuditTrailMapper.insert(tblAuditTrail);

    }

    @Override
    public void saveStatusLog(Object d,Integer status) {
        //status  状态值建议保存，前端方便解析。但需求让前端解析json数据中的状态字段，json状态字段不是固定的。 此处统一成states 字段
        if(d == null) {
            log.warn("===save  status log empty ===");
            return;
        }
        try {
            Class<?> thisClass = d.getClass();
            String objId = null;
            String objSubId = null;
            String tableName = getTableName(thisClass);
            List<Field> allField = Kit.getAllField(thisClass);
            for (Field field : allField) {
                try {
                    log.info("field:{}",field.getName());
                    field.setAccessible(true);
                    LogAnalysisAnnexTag logAnalysisAnnexTag = field.getAnnotation(LogAnalysisAnnexTag.class);
                    if(logAnalysisAnnexTag != null && logAnalysisAnnexTag.analysis()) {
                        objSubId = field.get(d).toString();
                    }
                    if(field.get(d)==null){

                    }else{
                        if("id".equals(field.getName())) {
                            objId = field.get(d).toString();
                        }

                    }
                }catch (Exception e){
                    log.error("赋值异常:",e);
                }finally {
                    field.setAccessible(false);
                }
            }
            String jsonInfo = JSON.toJSONString(d);
            JSONObject o = (JSONObject) JSON.toJSON(d);
            if(o != null) {
                //统一状态字段
                o.put("status", status);
                jsonInfo = o.toJSONString();
            }
            this.saveTblAuditTrail(objId,objSubId,5, jsonInfo,tableName);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public  String getTableName(Class<?> classes) {
        String tableName = "";
        if(classes == null) {
            return tableName;
        }
        while (classes != Object.class) {
            Table tableAnnotation = classes.getAnnotation(Table.class);
            if(tableAnnotation!= null) {
                tableName = tableAnnotation.name();
                return tableName;
            }
            classes = classes.getSuperclass();
            getTableName(classes);
        }
        return tableName;
    }
}